<?php
namespace App\Model;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Model\SystemConfig;
use Carbon\Carbon;

class FamilyCompetition extends BaseModel
{
    protected $connection = 'api';
    protected $systemTable = 'system_config';
    protected $user_table = 'user';
    protected $jdStream_table = 'finance_jd_stream';
    protected $diamondStream_table = 'finance_diamond_stream';

    protected $activityConn = 'activity';
    protected $fc_event_table = 'familycompetition_event';
    protected $fc_stat_table = 'familycompetition_statistics';
    protected $fc_stat_shop_table = 'familycompetition_shop_statistics';

    protected $excelOutTable = 'all_execel_out';//数据导出表

    //全家总动员获取配置
    public function getConfig(Request $request)
    {
        //全家总动员押注配置
        $stake = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_stake')->first();
        $stake = objToArray($stake);
        $stake = json_decode($stake['value'], true);
        $result['stake'] = [];
        foreach($stake as $key=>$val){
            $result['stake'][] = [
                'id' => $key,
                'price' => $val,
            ];
        }

        //全家总动员整体押注金豆数
        $maxPrice = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_max')->first();
        $maxPrice = objToArray($maxPrice);
        $result['maxPrice'] = empty($maxPrice['value']) ? 0 : $maxPrice['value'];

        //全家总动员开奖下限值
        $maxPrice = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_reward_min')->first();
        $maxPrice = objToArray($maxPrice);
        $result['rewardMin'] = empty($maxPrice['value']) ? 0 : $maxPrice['value'];

        //全家总动员开奖上限值
        $maxPrice = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_reward_max')->first();
        $maxPrice = objToArray($maxPrice);
        $result['rewardMax'] = empty($maxPrice['value']) ? 0 : $maxPrice['value'];

        //全家总动员飘屏通知下限值
        $maxPrice = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_screen_min')->first();
        $maxPrice = objToArray($maxPrice);
        $result['screenMin'] = empty($maxPrice['value']) ? 0 : $maxPrice['value'];

        //全家总动员利润率
        $profitRate = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_profit_rate')->first();
        $profitRate = objToArray($profitRate);
        $result['profitRate'] = empty($profitRate['value']) ? 0 : $profitRate['value'];

        return $result;
    }

    //全家总动员更新配置
    public function configUpdate(Request $request)
    {
        $type = (int) $request->input('type');

        $data = [];
        //全家总动员押注配置
        if($type == 1) {
            $id = (int) $request->input('id');
            $price = (int) $request->input('price');
            if(empty($id) || $price<1) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_stake')->first();
            $configInfo = objToArray($configInfo);
            $stake = json_decode($configInfo['value'], true);
            $stake[$id] = $price;
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => json_encode($stake),
            ];
        }
        //全家总动员整体押注金豆数
        if($type == 2) {
            $maxPrice = (int) $request->input('maxPrice');
            if(empty($maxPrice)) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_max')->first();
            $configInfo = objToArray($configInfo);
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => $maxPrice,
            ];
        }
        //全家总动员开奖下限值
        if($type == 3) {
            $maxPrice = (int) $request->input('maxPrice');
            if(empty($maxPrice)) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_reward_min')->first();
            $configInfo = objToArray($configInfo);
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => $maxPrice,
            ];
        }
        //全家总动员开奖上限值
        if($type == 4) {
            $maxPrice = (int) $request->input('maxPrice');
            if(empty($maxPrice)) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_reward_max')->first();
            $configInfo = objToArray($configInfo);
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => $maxPrice,
            ];
        }
        //全家总动员飘屏通知下限值
        if($type == 5) {
            $maxPrice = (int) $request->input('maxPrice');
            if(empty($maxPrice)) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_screen_min')->first();
            $configInfo = objToArray($configInfo);
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => $maxPrice,
            ];
        }
        //全家总动员利润率
        if($type == 6) {
            $maxPrice = (int) $request->input('maxPrice');
            if(empty($maxPrice)) {
                return [
                    'code' => 50001,
                    'msg' => '参数错误',
                ];
            }
            if($maxPrice<1 || $maxPrice>100){
                return [
                    'code' => 50001,
                    'msg' => '利润率必须是整数 0到100',
                ];
            }

            $configInfo = DB::connection($this->connection)->table($this->systemTable)->where('key', 'familyCompetition_profit_rate')->first();
            $configInfo = objToArray($configInfo);
            $data = [
                'id' => $configInfo['id'],
                'key' => $configInfo['key'],
                'desc' => $configInfo['desc'],
                'type' => $configInfo['type'],
                'value' => $maxPrice,
            ];
        }

        if(empty($data)) {
            return [
                'code' => 50001,
                'msg' => '参数错误',
            ];
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/system/config/update', $data, 'json', 'POST');
        if ($res['code'] !== 0) {
            return [
                'code' => 50000,
                'msg' => '失败',
            ];
        }

        return 1;
    }

    //全家总动员统计整体数据
    public function statSearchAll(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        if(empty($date_st) || empty($date_ed)) {
            return [
                'code' => 50000,
                'msg' => '日期必须选择',
            ];
        }
        $date_st = date("Ymd", strtotime($date_st));
        $date_ed = date("Ymd", strtotime($date_ed));
        $time_st = date("Y-m-d", strtotime($date_st)).' 00:00:00';
        $time_ed = date("Y-m-d", strtotime($date_ed)).' 23:59:59';

        $info_1 = DB::connection($this->activityConn)->table($this->fc_stat_table)
            ->selectRaw('sum(stakeNumAll) as stakeNumAll, sum(stakeNum) as stakeNum, sum(stakePriceAll) as stakePriceAll, sum(rewardPriceAll) as rewardPriceAll')
            ->where('ymd', '>=', $date_st)
            ->where('ymd', '<=', $date_ed)
            ->first();
        $info_1 = objToArray($info_1);

        $info_2 = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('count(1) as stakeNumAll, sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('poolId', '<', 10)
            ->first();
        $info_2 = objToArray($info_2);

        $info_3 = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('count(1) as stakeNumAll, sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('poolId', '>', 10)
            ->where('poolId', '<', 100)
            ->first();
        $info_3 = objToArray($info_3);

        $info_4 = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('count(1) as stakeNumAll, sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('poolId', '>', 100)
            ->where('poolId', '<', 1000)
            ->first();
        $info_4 = objToArray($info_4);

        
        $userNum = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('count(DISTINCT user_id) as userNum')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->first();
        $userNum = objToArray($userNum);

        $data = [];
        //参与人数
        $data['userNum'] = $userNum['userNum'];
        //押注次数
        $data['stakeNumAll'] = $info_1['stakeNumAll'];
        //押中次数
        $data['stakeNum'] = $info_1['stakeNum'];
        //消耗金豆数量
        $data['stakePriceAll'] = $info_1['stakePriceAll'];
        //产出金豆数量
        $data['rewardPriceAll'] = $info_1['rewardPriceAll'];
        //利润金豆数量 消耗-产出
        $data['porfitNum'] = $data['stakePriceAll'] - $data['rewardPriceAll'];
        //利润率 利润金豆/消耗金豆
        $data['porfitRate'] = empty($data['stakePriceAll']) ? 0 : round($data['porfitNum']/$data['stakePriceAll'], 6);
        //返奖率    产出金豆/消耗金豆
        $data['returnRate'] = empty($data['stakePriceAll']) ? 0 : round($data['rewardPriceAll']/$data['stakePriceAll'], 6);
        //单赛道次数
        $data['stakeNum_1'] = $info_2['stakeNumAll'];
        //单赛道消耗金豆数量
        $data['stakePrice_1'] = $info_2['stakePriceAll'];
        //双赛道次数
        $data['stakeNum_2'] = $info_3['stakeNumAll'];
        //双赛道消耗金豆数量
        $data['stakePrice_2'] = $info_3['stakePriceAll'];
        //三赛道次数
        $data['stakeNum_3'] = $info_4['stakeNumAll'];
        //三赛道消耗金豆数量
        $data['stakePrice_3'] = $info_4['stakePriceAll'];

        return $data;
    }

    //全家总动员统计单期数据
    public function statGameEvery(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');

        $query = DB::connection($this->activityConn)->table($this->fc_stat_table)->orderBy('id', 'desc');
        if(!empty($date_st)) {
            $date_st = date("Ymd", strtotime($date_st));
            $query = $query->where('ymd', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = date("Ymd", strtotime($date_ed));
            $query = $query->where('ymd', '<=', $date_ed);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        foreach($result['data'] as $key=>$val) {
            //利润金豆数量 消耗-产出
            $val['porfitNum'] = $val['stakePriceAll'] - $val['rewardPriceAll'];
            //利润率 利润金豆/消耗金豆
            $val['porfitRate'] = empty($val['stakePriceAll']) ? 0 : round($val['porfitNum']/$val['stakePriceAll'], 6);
            //返奖率    产出金豆/消耗金豆
            $val['returnRate'] = empty($val['stakePriceAll']) ? 0 : round($val['rewardPriceAll']/$val['stakePriceAll'], 6);
            $result['data'][$key] = $val;
        }

        return $result;
    }

    //全家总动员用户参与明细
    public function statUserInfo(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $uuid = $request->input('uuid');
        $limit = (int) $request->input('limit', 10);
        $page = (int) $request->input('page', 1);
        if(empty($date_st) || empty($date_ed)) {
            return [
                'code' => 50000,
                'msg' => '日期必须选择',
            ];
        }

        $page = ($page < 1) ? 1 : $page;
        $result = ['list'=>[], 'total'=>0, 'page'=>$page, 'limit'=>$limit];

        $date_st = date("Ymd", strtotime($date_st));
        $date_ed = date("Ymd", strtotime($date_ed));
        $time_st = date("Y-m-d", strtotime($date_st)).' 00:00:00';
        $time_ed = date("Y-m-d", strtotime($date_ed)).' 23:59:59';

        $userIds = [];
        //获取日期内的参与过的用户
        if(empty($user_id) && empty($uuid)) {
            $userIds = DB::connection($this->activityConn)->table($this->fc_event_table)
                ->where('created_at', '>=', $time_st)
                ->where('created_at', '<=', $time_ed)
                ->distinct()
                ->pluck('user_id');
            $userIds = objToArray($userIds);
        }else{
            if(!empty($user_id)) {
                $userInfo = DB::connection($this->connection)->table($this->user_table)->where('user_id', $user_id)->first();
            }
            if(!empty($uuid)) {
                $userInfo = DB::connection($this->connection)->table($this->user_table)->where('uuid', $uuid)->first();
            }
            if(empty($userInfo)) {
                return [
                    'code' => 50000,
                    'msg' => '搜索用户不存在',
                ];
            }
            $userInfo = objToArray($userInfo);
            $userIds = [$userInfo['user_id']];
        }
        $result['total'] = count($userIds);
        if(empty($userIds)) {
            return $result;
        }
        
        //分页
        sort($userIds);
        //获取用户信息
        $userList = DB::connection($this->connection)->table($this->user_table)->select('user_id','uuid','nickname')->whereIn('user_id', $userIds)->get();
        $userList = objToArray($userList);

        $info_1 = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('user_id, count(DISTINCT gameNum) as joinNum, count(1) as stakeNumAll, sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->whereIn('user_id', $userIds)
            ->groupBy('user_id')
            ->get();
        $info_1 = objToArray($info_1);
        $info_1 = array_column($info_1, null, 'user_id');

        $info_2 = DB::connection($this->activityConn)->table($this->fc_event_table)
            ->selectRaw('user_id, count(1) as stakeNum, sum(rewardPrice) as rewardPriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('status', 1)
            ->whereIn('user_id', $userIds)
            ->groupBy('user_id')
            ->get();
        $info_2 = objToArray($info_2);
        $info_2 = array_column($info_2, null, 'user_id');

        $info_3 = DB::connection($this->connection)->table($this->diamondStream_table)
            ->selectRaw('user_id, sum(diamond_value) as buyGoodDiamondNum')
            ->where('change_time', '>=', $time_st)
            ->where('change_time', '<=', $time_ed)
            ->where('diamond_type', 100)
            ->whereIn('user_id', $userIds)
            ->groupBy('user_id')
            ->get();
        $info_3 = objToArray($info_3);
        $info_3 = array_column($info_3, null, 'user_id');

        $info_4 = DB::connection($this->connection)->table($this->jdStream_table)
            ->selectRaw('user_id, sum(change_value) as buyGiftJdNum')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('jd_type', 51)
            ->whereIn('user_id', $userIds)
            ->groupBy('user_id')
            ->get();
        $info_4 = objToArray($info_4);
        $info_4 = array_column($info_4, null, 'user_id');

        foreach($userList as $val) {
            $data = [];
            //用户ID
            $data['userId'] = $val['user_id'];
            //用户uuid
            $data['uuid'] = $val['uuid'];
            //用户昵称
            $data['nickname'] = $val['nickname'];
            //参与次数
            $data['joinNum'] = empty($info_1[$val['user_id']]['joinNum']) ? 0 : $info_1[$val['user_id']]['joinNum'];
            //押注次数
            $data['stakeNumAll'] = empty($info_1[$val['user_id']]['stakeNumAll']) ? 0 : $info_1[$val['user_id']]['stakeNumAll'];
            //押中次数
            $data['stakeNum'] = empty($info_2[$val['user_id']]['stakeNum']) ? 0 : $info_2[$val['user_id']]['stakeNum'];
            //消耗金豆数量
            $data['stakePriceAll'] = empty($info_1[$val['user_id']]['stakePriceAll']) ? 0 : $info_1[$val['user_id']]['stakePriceAll'];
            //产出金豆数量
            $data['rewardPriceAll'] = empty($info_2[$val['user_id']]['rewardPriceAll']) ? 0 : $info_2[$val['user_id']]['rewardPriceAll'];
            //利润金豆数量 产出-消耗
            $data['porfitNum'] =  $data['rewardPriceAll'] - $data['stakePriceAll'];
            //利润率 利润金豆/消耗金豆
            $data['porfitRate'] = empty($data['stakePriceAll']) ? 0 : round($data['porfitNum']/$data['stakePriceAll'], 6);
            //购买道具钻石数
            $data['buyGoodDiamondNum'] = abs(empty($info_3[$val['user_id']]['buyGoodDiamondNum']) ? 0 : $info_3[$val['user_id']]['buyGoodDiamondNum']);
            //兑换礼物金豆数
            // $data['buyGiftJdNum'] = empty($info_4[$val['user_id']]['buyGiftJdNum']) ? 0 : $info_4[$val['user_id']]['buyGiftJdNum'];
            $result['list'][] = $data;
        }

        return $result;
    }

    //全家总动员商店兑换数据
    public function statShopList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');

        $query = DB::connection($this->activityConn)->table($this->fc_stat_shop_table)->orderBy('id', 'desc');
        if(!empty($date_st)) {
            $date_st = date("Ymd", strtotime($date_st));
            $query = $query->where('date', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $date_ed = date("Ymd", strtotime($date_ed));
            $query = $query->where('date', '<=', $date_ed);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        foreach($result['data'] as $key=>$val) {
            $val['date'] = date("Y-m-d", strtotime($val['date']));

            $result['data'][$key] = $val;
        }
        //如果日期查了今天的
        if(!empty($date_st) && !empty($date_ed)) {
            $today = date("Y-m-d", time());
            $time_st = $today.' 00:00:00';
            $time_ed = $today.' 23:59:59';
            if(strtotime($date_st) == strtotime($today)) {
                $jdInfo = DB::connection($this->connection)->table($this->jdStream_table)
                    ->selectRaw('count(DISTINCT user_id) as userNum, count(1) as buyNum, sum(change_value) as buyGiftJdNum')
                    ->where('created_at', '>=', $time_st)
                    ->where('created_at', '<=', $time_ed)
                    ->where('jd_type', 51)
                    ->first();
                $jdInfo = self::objToArray($jdInfo);

                $diamondInfo = DB::connection($this->connection)->table($this->diamondStream_table)
                    ->selectRaw('count(DISTINCT user_id) as userNum, count(1) as buyNum, sum(diamond_value) as buyGoodDiamondNum')
                    ->where('change_time', '>=', $time_st)
                    ->where('change_time', '<=', $time_ed)
                    ->where('diamond_type', 100)
                    ->first();
                $diamondInfo = self::objToArray($diamondInfo);

                $log = [];
                $log['id'] = 0;
                $log['date'] = $today;
                $log['jdBuyUserNum'] = empty($jdInfo['userNum']) ? 0 : $jdInfo['userNum'];
                $log['jdBuyNum'] = empty($jdInfo['buyNum']) ? 0 : $jdInfo['buyNum'];
                $log['jdBuyGiftJdNum'] = empty($jdInfo['buyGiftJdNum']) ? 0 : $jdInfo['buyGiftJdNum'];
                $log['diamondBuyUserNum'] = empty($diamondInfo['userNum']) ? 0 : $diamondInfo['userNum'];
                $log['diamondBuyNum'] = empty($diamondInfo['buyNum']) ? 0 : $diamondInfo['buyNum'];
                $log['buyGoodDiamondNum'] = empty($diamondInfo['buyGoodDiamondNum']) ? 0 : $diamondInfo['buyGoodDiamondNum'];
                $log['jdBuyGiftJdNum'] = abs($log['jdBuyGiftJdNum']);
                $log['buyGoodDiamondNum'] = abs($log['buyGoodDiamondNum']);
                $log['created_at'] = date("Y-m-d H:i:s", time());;
                $result['data'][] = $log;
            }
        }

        return $result;
    }

}
